import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import { Stage, Layer, Line } from "react-konva";

export const WhiteBoard = forwardRef((props, ref) => {
  const [lines, setLines] = useState([]);
  const [isDrawing, setIsDrawing] = useState(false);
  const { clearHooks, paintSettings } = props.settings;
  const [isClear, setIsClear] = clearHooks;

  const stageRef = useRef(null);

  useImperativeHandle(ref,() => ({
    getStage:() => stageRef.current,
  }))

  const handleMouseDown = (e) => {
    if (!paintSettings.selectedPainter) {
      return;
    }
    setIsDrawing(true);
    const stage = e.target.getStage();
    const pos = stage.getPointerPosition();
    setLines([
      ...lines,
      {
        points: [pos.x, pos.y],
        stroke: paintSettings.stroke,
        strokeWidth: paintSettings.strokeWidth,
      },
    ]);
  };

  const handleMouseMove = (e) => {
    if (!isDrawing) {
      return;
    }
    const stage = e.target.getStage();
    const point = stage.getPointerPosition();
    const lastLine = lines[lines.length - 1];
    const newPoints = lastLine.points.concat([point.x, point.y]);
    lastLine.points = newPoints;
    setLines(lines.slice(0, lines.length - 1).concat(lastLine));
  };

  const handleMouseUp = () => {
    setIsDrawing(false);
  }; // use context

  const clearCanvas = () => {
    setLines([]);
  };

  useEffect(() => {
    clearCanvas();
    setIsClear(false);
  }, [isClear]);

  return (
    <div>
      <Stage
        width={window.innerWidth}
        height={window.innerHeight}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        ref={stageRef}
      >
        <Layer>
          {lines.map((line, i) => (
            <Line
              key={i}
              points={line.points}
              stroke={line.stroke}
              strokeWidth={line.strokeWidth}
            />
          ))}
        </Layer>
      </Stage>
    </div>
  );
});
